const Joi = require('joi');

/**
 * User validation schemas for API V2
 * Enhanced validation with more comprehensive rules
 */

// V2 User creation schema with enhanced validation
const userCreateSchema = Joi.object({
  username: Joi.string()
    .alphanum()
    .min(3)
    .max(30)
    .required()
    .messages({
      'string.alphanum': 'Username must contain only letters and numbers',
      'string.min': 'Username must be at least 3 characters long',
      'string.max': 'Username cannot exceed 30 characters',
      'any.required': 'Username is required'
    }),
    
  email: Joi.string()
    .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net', 'org', 'edu', 'gov'] } })
    .required()
    .messages({
      'string.email': 'Please provide a valid email address',
      'any.required': 'Email is required'
    }),
    
  password: Joi.string()
    .min(8)
    .max(128)
    .pattern(new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]'))
    .required()
    .messages({
      'string.min': 'Password must be at least 8 characters long',
      'string.max': 'Password cannot exceed 128 characters',
      'string.pattern.base': 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character',
      'any.required': 'Password is required'
    }),
    
  role: Joi.string()
    .valid('user', 'admin', 'moderator')
    .default('user')
    .messages({
      'any.only': 'Role must be one of: user, admin, moderator'
    }),
    
  terms_accepted: Joi.boolean()
    .valid(true)
    .required()
    .messages({
      'any.only': 'Terms and conditions must be accepted',
      'any.required': 'Terms acceptance is required'
    })
});

// V2 User update schema
const userUpdateSchema = Joi.object({
  username: Joi.string()
    .alphanum()
    .min(3)
    .max(30)
    .messages({
      'string.alphanum': 'Username must contain only letters and numbers',
      'string.min': 'Username must be at least 3 characters long',
      'string.max': 'Username cannot exceed 30 characters'
    }),
    
  email: Joi.string()
    .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net', 'org', 'edu', 'gov'] } })
    .messages({
      'string.email': 'Please provide a valid email address'
    }),
    
  role: Joi.string()
    .valid('user', 'admin', 'moderator')
    .messages({
      'any.only': 'Role must be one of: user, admin, moderator'
    }),
    
  status: Joi.string()
    .valid('active', 'inactive', 'suspended')
    .messages({
      'any.only': 'Status must be one of: active, inactive, suspended'
    })
}).min(1).messages({
  'object.min': 'At least one field must be provided for update'
});

/**
 * Validation middleware for V2 user creation
 */
const validateUser = (req, res, next) => {
  const { error, value } = userCreateSchema.validate(req.body, { 
    abortEarly: false,
    stripUnknown: true 
  });

  if (error) {
    const errors = error.details.map(detail => ({
      field: detail.path.join('.'),
      message: detail.message,
      code: detail.type
    }));

    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors,
      error_code: 'VALIDATION_ERROR',
      timestamp: new Date().toISOString(),
      api_version: '2.0'
    });
  }

  req.body = value;
  next();
};

/**
 * Validation middleware for V2 user updates
 */
const validateUserUpdate = (req, res, next) => {
  const { error, value } = userUpdateSchema.validate(req.body, { 
    abortEarly: false,
    stripUnknown: true 
  });

  if (error) {
    const errors = error.details.map(detail => ({
      field: detail.path.join('.'),
      message: detail.message,
      code: detail.type
    }));

    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors,
      error_code: 'VALIDATION_ERROR',
      timestamp: new Date().toISOString(),
      api_version: '2.0'
    });
  }

  req.body = value;
  next();
};

module.exports = {
  validateUser,
  validateUserUpdate,
  userCreateSchema,
  userUpdateSchema
};